package com.jp.knowledge.wxapi;

import com.jiayen.util.ToasUtil;
import com.jp.knowledge.comm.JpApplication;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler{

	public static final String WECHAT_PAY = "wechatPay";
	public static final String WECHAT_PAY_ERR_CODE = "wechatPayErrCode";

	private IWXAPI api;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		api = WXAPIFactory.createWXAPI(this, JpApplication.weixin_appid, true);
		api.registerApp(JpApplication.weixin_appid);
		api.handleIntent(getIntent(), this);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {}

	@Override
	public void onResp(BaseResp resp) {
		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
			Intent broadcastIntent = new Intent(WECHAT_PAY);
			broadcastIntent.putExtra(WECHAT_PAY_ERR_CODE, resp.errCode);
			LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
			if(resp.errCode == BaseResp.ErrCode.ERR_OK) {
				ToasUtil.toast(this, "支付成功");
			} else if(resp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
				ToasUtil.toast(this, "取消支付");
			} else if(resp.errCode == BaseResp.ErrCode.ERR_COMM) {
				ToasUtil.toast(this, "支付失败");
			}
		}
		finish();
	}
}